/*
 * File Name：ProgressCircle.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ProgressCircle.java
 * Modify By：res-mingyang
 * Modify Date：2015-7-24
 * Modify Type：Add
 */
package com.ciwong.epaper.util.download;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.RectF;
import android.os.Looper;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.ciwong.epaper.util.DeviceUtil;
import com.ciwong.libs.utils.DeviceUtils;

/**
 *
 */
public class DownLoadRateView extends AppCompatImageView {
    private Context mContext;

    private int RADIU;

    private final float PERIMETER = 0.9f;

    private int mCurrentStatu;

    private Paint paint;
    private Paint 虚线paint;
    private float progress, animationProgress;

    private int degree;

    private final int NORMAL_COLOR = Color.parseColor("#52CC8F");

    private final int ERROR_COLOR = Color.parseColor("#C8C8C8");

    private final int DOWNLOADING_COLOR = Color.parseColor("#52CC8F");

    private final int RED_COLOR = Color.parseColor("#FF0000");
//    private final int RED_COLOR = Color.parseColor("#FFFFFF");

    private final int GRAY_COLOR = Color.parseColor("#B0B1B0");

    private final int ARROW_COLOR = Color.parseColor("#d4d4d4");

    private int mCurrentColor;

    private RectF rectF;

    private Canvas canvas;

    public DownLoadRateView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }

    public DownLoadRateView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DownLoadRateView(Context context) {
        this(context, null);
    }

    private void init() {
        this.mCurrentStatu = DownloadStatus.STATUS_NORMAL;
        this.mCurrentColor = NORMAL_COLOR;
        paint = new Paint();
        虚线paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(mCurrentColor);
    }

    PathEffect effects = new DashPathEffect(new float[]{10, 10, 10, 10}, 1);

    @Override
    protected void onDraw(Canvas canvas) {
        animationProgress = 0f;
        this.canvas = canvas;
        paint.setColor(mCurrentColor);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
        paint.setAlpha(255);
        int centerX = getMeasuredWidth() / 2;
        int centerY = getMeasuredHeight() / 2;
        if (RADIU == 0) {
            this.RADIU = (int) (getMeasuredHeight() * 0.48f);
        }
        super.onDraw(canvas);
        setRectF();
        if (!(mCurrentStatu == DownloadStatus.STATUS_LOADING
                || mCurrentStatu == DownloadStatus.STATUS_COMPLETED || mCurrentStatu == DownloadStatus.STATUS_NORMAL)) {
            if (mCurrentStatu == DownloadStatus.STATUS_FAILED) {
                paint.setColor(RED_COLOR);
            }

            if (mCurrentStatu == DownloadStatus.STATUS_DOWNLOADING
                    || mCurrentStatu == DownloadStatus.STATUS_PAUSE) {
                paint.setStyle(Paint.Style.STROKE);//空心
                paint.setColor(Color.parseColor("#CCCCCC"));
//                Path path = new Path();
                //通过moveto，lineto的x，y坐标确定虚线实横，纵，还是倾斜
//                path.moveTo(0, 10);//Set the beginning of the next contour to the point (x,y)
//                path.lineTo(480, 10);//Add a line from the last point to the specified point (x,y).
                //DashPathEffect  可以使用DashPathEffect来创建一个虚线的轮廓(短横线/小圆点)，而不是使用实线
                //float[] { 5, 5, 5, 5 }值控制虚线间距，密度

                paint.setPathEffect(effects);
//                canvas.drawPath(path, paint);
                canvas.drawCircle(centerX, centerY, RADIU, paint);// 圆形
            } else {
                paint.setColor(mCurrentColor);
                canvas.drawArc(rectF, 35, -360, false, paint);// 弧形
            }
        }
        paint.setPathEffect(null);
        if (mCurrentStatu == DownloadStatus.STATUS_DOWNLOADING) {
            drawDownloading(255, true);
            return;
        } else if (mCurrentStatu == DownloadStatus.STATUS_LOADING) {
            degree = degree + 5;
            canvas.rotate(degree, centerX, centerY);
            invalidate();
            canvas.drawArc(rectF, -90, 360 * PERIMETER, false, paint);
        }
        switch (mCurrentStatu) {
            case DownloadStatus.STATUS_NORMAL:
//                drawNormal_icon(centerX, centerY);
                drawNormal_circle(centerX, centerY);
                break;
            case DownloadStatus.STATUS_COMPLETED:
                animationProgress = 1f;
                drawCompleted_circle(centerX, centerY);
                break;
            case DownloadStatus.STATUS_PAUSE:
                drawPause(centerX, centerY, 255, true);
                break;
            case DownloadStatus.STATUS_FAILED:
            case DownloadStatus.STATUS_FAILED_SDISFULL:
            case DownloadStatus.STATUS_FAILED_UNZIP:
                drawFailed(centerX, centerY);
                break;
        }
    }

    private void drawCompleted_circle(int centerX, int centerY) {
        canvas.drawCircle(centerX, centerY, RADIU, paint);// 圆形
    }

    private void drawNormal_circle(int centerX, int centerY) {
        paint.setPathEffect(effects);
//                canvas.drawPath(path, paint);
        paint.setColor(Color.parseColor("#CCCCCC"));
        canvas.drawCircle(centerX, centerY, RADIU, paint);// 圆形
        paint.setPathEffect(null);
    }

    private void drawNormal_icon(int centerX, int centerY) {
//        if (animationProgress >= 0 && animationProgress <= 0.5f) {

        float stopVerticalY = centerY * 125 / 100;
        //中间竖线
        canvas.drawLine(centerX, centerY * 65 / 100, centerX, stopVerticalY, paint);
        // 下
        // canvas.drawLine(centerX * 3 / 4 + centerX * animationProgress /
        // 2,
        // centerY * 5 / 4 + centerY / 16,
        // centerX * 5 / 4 - centerX * animationProgress / 2,
        // centerY * 5 / 4 + centerY / 16, paint);
        float startY = centerY * 100 / 100;
        float startLeftX = centerX * 75 / 100;
        //箭头左边斜线
        canvas.drawLine(startLeftX, startY, centerX, stopVerticalY, paint);
        // 箭头右边斜线
        float startRightX = centerX + (centerX - startLeftX);
        canvas.drawLine(startRightX, startY, centerX, stopVerticalY, paint);
        //下方横线
        float startBottomLeftX = centerX * 58 / 100;
        float BottomY = centerY * 145 / 100;
        float stopBottomRightX = centerX + (centerX - startBottomLeftX);
        canvas.drawLine(startBottomLeftX, BottomY, stopBottomRightX, BottomY, paint);

        //下方左边斜线
        float startSlashLeftX = centerX * 48 / 100;
        float startSlashY = stopVerticalY;
        float stopSlashLeftX = startBottomLeftX;
        canvas.drawLine(startSlashLeftX, startSlashY, stopSlashLeftX, BottomY, paint);
        //下方右边斜线
        float startSlashRightX = centerX + (centerX - startSlashLeftX);
        float startSlashRightY = stopVerticalY;
        float stopSlashRightX = stopBottomRightX;
        canvas.drawLine(startSlashRightX, startSlashRightY, stopSlashRightX, BottomY, paint);

//        } else if (animationProgress > 0.5f && animationProgress <= 1) {
//            canvas.drawLine(centerX, centerY / 2, centerX,
//                    centerY * 5 / 4
//                            - centerY * 3 / 4 * (2 * animationProgress - 1f),
//                    paint);
//        }
    }

    private void drawDownloading(int alpha, boolean isDrawArc) {
        String text = String.valueOf(Math.round(progress * 100)) + "%";
        if (isDrawArc) {
            paint.setColor(DOWNLOADING_COLOR);
            canvas.drawArc(rectF, -90, 360 * progress, false, paint);
        }
        paint.setStrokeWidth(1);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(DeviceUtils.dip2px(18));
        float tX = (getMeasuredWidth() - getFontlength(paint, text)) / 2;
        float tY = (getMeasuredHeight() - getFontHeight(paint)) / 2
                + getFontLeading(paint);
        paint.setAlpha(alpha);
        paint.setColor(DOWNLOADING_COLOR);
        canvas.drawText(text, tX, tY, paint);
    }


    private void drawPause(int centerX, int centerY, int alpha,
                           boolean isDrawArc) {
        if (isDrawArc) {
            canvas.drawArc(rectF, -90, 360, false, paint);
        }
        paint.setStrokeWidth(3);
        paint.setAlpha(alpha);
        canvas.drawLine(centerX - centerX / 8, centerY - centerY / 5,
                centerX - centerX / 8, centerY + centerY / 5, paint);
        canvas.drawLine(centerX + centerX / 8, centerY - centerY / 5,
                centerX + centerX / 8, centerY + centerY / 5, paint);
    }

    private void drawFailed(int centerX, int centerY) {
        paint.setColor(NORMAL_COLOR);
        // canvas.drawLine(centerX, centerY,
        // centerX - centerX / 4 * (1 - animationProgress),
        // centerY - centerY / 4 * (1 - animationProgress), paint);
        // canvas.drawLine(centerX, centerY,
        // centerX + centerX / 4 * (1 - animationProgress),
        // centerY - centerY / 4 * (1 - animationProgress), paint);
        // canvas.drawLine(centerX, centerY,
        // centerX - centerX / 4 * (1 - animationProgress),
        // centerY + centerY / 4 * (1 - animationProgress), paint);
        // canvas.drawLine(centerX, centerY,
        // centerX + centerX / 4 * (1 - animationProgress),
        // centerY + centerY / 4 * (1 - animationProgress), paint);
        // 小圆点
        canvas.drawCircle(centerX, centerY * 5 / 4, 2, paint);
        Paint pointPaint = paint;
        pointPaint.setStrokeWidth(5);
        // 中间竖线
        canvas.drawLine(centerX, centerY / 3 * 2, centerX, centerY * 10 / 9,
                pointPaint);
        // canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
        // R.mipmap.icon_submit_fail_tip), 0, 0, paint);
    }


    public void updateDownloadProgress(float progress) {
        this.progress = progress;
        this.mCurrentStatu = DownloadStatus.STATUS_DOWNLOADING;
        invalidate();
    }

    public void setIsError(boolean isError) {
        this.mCurrentColor = isError ? ERROR_COLOR : NORMAL_COLOR;
    }

    public void initToNormal() {
        this.mCurrentStatu = DownloadStatus.STATUS_NORMAL;
        invalidate();
    }

    public void initToLoading() {
        progress = 0;
        this.mCurrentStatu = DownloadStatus.STATUS_LOADING;
        invalidate();
    }

    public void initToDownloading() {
        this.mCurrentStatu = DownloadStatus.STATUS_DOWNLOADING;
        invalidate();
    }

    public void initToCompleted() {
        this.mCurrentStatu = DownloadStatus.STATUS_COMPLETED;
        invalidate();
    }

    public void initToPause() {
        this.mCurrentStatu = DownloadStatus.STATUS_PAUSE;
        invalidate();
    }

    public void initToFAILED() {
        this.mCurrentStatu = DownloadStatus.STATUS_FAILED;
        invalidate();
    }

    /**
     * 更新ui
     */
    @Override
    public void invalidate() {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            super.invalidate();
        } else {
            super.postInvalidate();
        }
    }

    private void setRectF() {
        if (rectF == null) {
            rectF = new RectF();
            rectF.left = getMeasuredWidth() / 2 - RADIU;
            rectF.top = getMeasuredHeight() / 2 - RADIU;
            rectF.right = getMeasuredWidth() / 2 + RADIU;
            rectF.bottom = getMeasuredHeight() / 2 + RADIU;
        }
    }

    /**
     * @return 返回指定笔和指定字符串的长度
     */
    public float getFontlength(Paint paint, String str) {
        return paint.measureText(str);
    }

    /**
     * @return 返回指定笔的文字高度
     */
    public float getFontHeight(Paint paint) {
        FontMetrics fm = paint.getFontMetrics();
        return fm.descent - fm.ascent;
    }

    /**
     * @return 返回指定笔离文字顶部的基准距离
     */
    public float getFontLeading(Paint paint) {
        FontMetrics fm = paint.getFontMetrics();
        return fm.leading - fm.ascent;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 sp
     */
    public static int px2sp(Context context, float pxValue) {
        final float scale = context.getResources()
                .getDisplayMetrics().scaledDensity;
        return (int) (pxValue / scale);
    }


}
